<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginData" label-width="80px" class="login-form">
      <h2>用户登录</h2>
      <el-form-item label="用户名" :validateStatus="loginData.username ? 'success' : 'error'">
        <el-input v-model="loginData.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" :validateStatus="loginData.password ? 'success' : 'error'">
        <el-input v-model="loginData.password" type="password" placeholder="请输入密码" @keyup.enter.native="submitLogin"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitLogin">登录</el-button>
        <el-button type="success" @click="goToRegister">注册</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { login } from '@/api/user'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 登录数据
const loginData = ref({
  username: '',
  password: ''
})

// 组件挂载时检查 token
onMounted(() => {
  const token = localStorage.getItem('token')
  if (token) {
    // 如果 token 存在，跳转到首页
    router.push('/activity-list')
  }
})

// 提交登录
const submitLogin = async () => {
  // 添加空值校验
  if (!loginData.value.username || !loginData.value.password) {
    ElMessage.error('用户名和密码不能为空');
    return;
  }

  try {
    const res = await login(loginData.value);
    console.log('登录响应:', res);
    if (res.code === 200) {
      ElMessage.success('登录成功！');
      localStorage.setItem('token', res.data);
      router.push('/activity-list');
    } else {
      ElMessage.error(res.msg || '登录失败');
    }
  } catch (error) {
    ElMessage.error(error.message || '网络错误，请重试');
  }
}

// 重置表单
const resetForm = () => {
  loginData.value.username = '';
  loginData.value.password = '';
};

// 前往注册页
const goToRegister = () => {
  router.push('/register');
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
}

.login-form {
  width: 400px;
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>